﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using haptic.src.engine.collisions;
using System.Diagnostics;
using haptic.src.engine.render;

namespace haptic.src.engine.scene
{
    [Serializable]
    public class CollisionNode : Node, IDebugDrawable
    {
        #region Constructors
        public CollisionNode()
        {
            m_eType = NodeType.E_COLLISION;
        }
        public CollisionNode(ICollider oCollider)
        {
            m_eType = NodeType.E_COLLISION;
            m_oCollider = oCollider;
        }
        #endregion

        #region Update
        public override void Update(Microsoft.Xna.Framework.GameTime oTime)
        {
            Debug.Assert(oParent != null);
            if (GetFlag(Flag.E_LOCAL_CHANGED))
            {
                m_mWorld = oParent.mWorld * oParent.mLocal;
                m_oCollider.SetCenter(m_mWorld.O);
                DisableFlag(Flag.E_LOCAL_CHANGED);
            }
        }
        #endregion

        #region Draw
        public override void DrawDebug(haptic.src.engine.debug.DebugRenderer oRenderer)
        {
            m_oCollider.DrawDebug(oRenderer);
        }
        #endregion

        #region Serialization
        public XmlSchema GetSchema()
        {
            return null;
        }
        public void WriteXml(XmlWriter w)
        {
            XmlSerializerNamespaces oNs = new XmlSerializerNamespaces();
            oNs.Add("", "");

            // sprite
            if (m_oCollider != null)
            {
                w.WriteStartElement("collider");
                w.WriteAttributeString("type", m_oCollider.GetType().ToString());
                XmlSerializer oSrlz = new XmlSerializer(m_oCollider.GetType());
                oSrlz.Serialize(w, m_oCollider, oNs);
                w.WriteEndElement();
            }
        }
        public void ReadXml(XmlReader r)
        {
            if (r.ReadToFollowing("collider"))
            {
                Type oType = Type.GetType(r.GetAttribute("type"));
                XmlSerializer oSrlz = new XmlSerializer(oType);
                r.ReadToDescendant(oType.Name);
                m_oCollider = (ICollider)oSrlz.Deserialize(r);
            }
        }
        #endregion

        #region Attributes
        private ICollider m_oCollider;
        public ICollider oCollider { get { return m_oCollider; } }
        #endregion
    }
}
